function addUser() {
    location.href = "./adAndUp.html";
}
function goHome() {
    console.log('回到首页');

}
// Popup
function openPopup() {
    document.getElementById('overlay').style.display = 'flex';
    document.getElementById('popup').style.display = 'block';
}
function closePopup() {
    document.getElementById('overlay').style.display = 'none';
    document.getElementById('popup').style.display = 'none';
}
// Page
function prevPage() {
    alert('上一页');
}
function nextPage() {
    alert('下一页');
}
// Edit
function userEdit(userId) {

    // 验证ID有效性
    if (!userId || isNaN(userId)) {
        console.error('无效的用户ID');
        return;
    }

    if (!confirm('确定要修改该用户信息吗？')) {
        return;
    }

    location.href = `./adAndUp.html?${userId}`;
}
// Delete
function userDel(userId) {

    // 验证ID有效性
    if (!userId || isNaN(userId)) {
        console.error('无效的用户ID');
        return;
    }

    fetch(`http://127.0.0.1:8000/User/${userId}`, {
        method: "DELETE",
    })
        .then(response => {
            if (response.status === 200) {
                console.log("删除成功");
                location.href = "./Users.html"

            } else {
                throw new Error(`删除失败，状态码：${response.status}`);
            }
        })
        .catch(error => {
            console.error("删除出错:", error);
            alert('删除失败，请重试');
        });
}
// SelectAll
function Users() {
    console.log(1);

    fetch(`http://127.0.0.1:8000/Users`, {
        method: "GET"
    }).then(res => {
        console.log(res);

        return res.json()
    })
        .then(data => {
            const newArr =
                data.data.map((item) => {
                    // let uobj = {
                    //     id: item.id,
                    //     userName: item.userName,
                    //     gender: item.gender,
                    //     age: item.age,
                    //     email: item.email,
                    //     registrationTime: item.registrationTime
                    // };
                    // let user = JSON.stringify(uobj)

                    return `
            <tr>
                <th>${item.id}</th>
                <th>${item.userName}</th>
                <th>${item.gender}</th>
                <th>${item.age}</th>
                <th>${item.email}</th>
                <th>${item.registrationTime}</th>
                <td>
                    <input class="update-btn" type="button" value="修改" onclick="userEdit(${item.id})">
                    <input class="delete-btn" type="button" value="删除" onclick="userDel(${item.id})">
                </td>
            </tr>
            `
                }).join("");


            document.querySelector("tbody").innerHTML = newArr;
        }

        )
}

window.addEventListener('DOMContentLoaded', () => { Users(); }

)
